package coderead.maven;

import coderead.maven.search.IndexShortSearch;
import coderead.maven.service.ArtifactInfoStore;
import coderead.maven.service.MavenIndexManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;

@Slf4j
@RequiredArgsConstructor
@EnableScheduling
@SpringBootApplication
public class MavenWebApp {
    private final IndexShortSearch indexShortSearch;
    private final MavenIndexManager indexManager;
    private final ArtifactInfoStore versionCountStore;

    public static void main(String[] args) {

        SpringApplication.run(MavenWebApp.class, args);
    }

    // 索引更新计划,每周三，凌晨5点
    @Scheduled(cron = "${index.update.cron}")
    public void update() {
        try {
            log.info("定时任务：远程索引更新");
            indexManager.update();
            log.info("定时任务：索引加载");
            indexShortSearch.reload();
            log.info("定时任务：索引更新成功");
        } catch (IOException e) {
            log.error("索引更新失败", e);
        }
    }

    // 每2小时 的15分 15秒 保存状态
    @Scheduled(cron = "${index.save.cron}")
    public void saveHot() {
        try {
            log.info("定时任务：索引状态更新");
            // 保存版本使用数
            versionCountStore.storeVersionCount();
            log.info("定时任务：索引状态更新成功");
        } catch (IOException e) {
            log.error("索引状态保存失败", e);
        }
    }
}
